package com.leetcode;

/**
 * 167. 两数之和 II - 输入有序数组
 * 循环二分查找
 */
public class Solution167_1 {
    public int[] twoSum(int[] numbers, int target) {
        int n = numbers.length;
        for (int i = 0; i < n - 1; i++) {
            int idx = binarySearch(numbers, target - numbers[i], i + 1, n - 1);
            if (idx != -1) {
                return new int[]{i + 1, idx + 1};
            }
        }
        throw new RuntimeException("not found");
    }

    private int binarySearch(int[] nums, int num, int left, int right) {
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == num) {
                return mid;
            } else if (nums[mid] > num) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
//        int[] numbers = new int[]{5, 25, 75};
//        int target = 100;
        int[] numbers = new int[]{12,13,23,28,43,44,59,60,61,68,70,86,88,92,124,125,136,168,173,173,180,199,212,221,227,230,277,282,306,314,316,321,325,328,336,337,363,365,368,370,370,371,375,384,387,394,400,404,414,422,422,427,430,435,457,493,506,527,531,538,541,546,568,583,585,587,650,652,677,691,730,737,740,751,755,764,778,783,785,789,794,803,809,815,847,858,863,863,874,887,896,916,920,926,927,930,933,957,981,997};
        int target = 542;
        int[] res = new Solution167().twoSum(numbers, target);
        for (int i = 0; i < res.length; i++) {
            System.out.println(res[i] + " ");
        }
    }
}
